package com.bawei.day14_service;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

public class Main2Activity extends AppCompatActivity {
    private MyService2.MyBinder myBinder;
    //和服务建立的链接
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder  = (MyService2.MyBinder) service;
            Log.d("ytx", "建立链接成功: ");
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("ytx", "链接失败: ");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        findViewById(R.id.bt_bind).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bind();
            }
        });
        findViewById(R.id.bt_unbind).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unbind();
            }
        });
        //调用服务里面的方法
        findViewById(R.id.bt_play).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myBinder.play();
            }
        });
    }
    private void unbind() {
        unbindService(connection);
    }
    private void bind() {
        Intent intent = new Intent(this,MyService2.class);
        //参数一 intent对象 参数二 绑定成功后建立的链接  参数三 绑定成功后服务会被自动创建
        bindService(intent,connection, Service.BIND_AUTO_CREATE);//
    }
}
